<template>
  <div class="cate-container mt50 mb60">
    <van-nav-bar
      fixed
      left-arrow
      @click-left="router.go(-1)"
      title="商品列表"
    ></van-nav-bar>
    <!-- 商品列表 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-card
          lazy-load
          @click="goGoods(item.id)"
          v-for="item in goodsList"
          :key="item.id"
          :price="item.price"
          :title="item.goodsname"
          :thumb="baseUrl + item.img"
        />
      </van-list>
    </van-pull-refresh>
    <van-empty
      v-if="goodsList.length === 0"
      description="暂无商品数据"
    ></van-empty>
  </div>
</template>

<script setup>
import { inject, onMounted, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";
import { usePager } from "@/plugins/hooks";
const router = useRouter();
const route = useRoute();
// 调用自定义hooks函数
const { page, size,totalCount,finished,loading,isLoading } = usePager();

const goodsList = ref([]);

const axios = inject("axios");
const baseUrl = inject("baseURL");
// 下拉刷新
const onRefresh = () => {
  // 开启下拉刷新loading
  isLoading.value = true;
  // 重新请求数据
  getGoodsList();
};

// 加载下一页数据
const onLoad = () => {
  if (goodsList.value.length < totalCount.value) {
    //开启loading效果
    loading.value = true;
    // 页码+1
    page.value += 1;
    // 根据最新页码请求数据
    getGoodsList();
  }
};

const goGoods = (id) => {
  router.push({ name: "goods", query: { id } });
};

const getGoodsList = () => {
  const { cateid } = route.query;
  if (!cateid) {
    showToast("参数错误");
    return router.push("/index");
  }
  const params = { page: page.value, size: size.value, cateid };
  axios.get("/getgoodslist", { params }).then((res) => {
    if (res.code === 200) {
      const { goodsData = [], total = 0 } = res.list;
      // 更新商品列表数组
      goodsList.value = [...goodsList.value, ...goodsData];
      // 更新数据总条数
      totalCount.value = total;
      setTimeout(() => {
        // 关闭上拉加载更多loading加载效果
        loading.value = false;
        // 关闭下拉更新loading
        isLoading.value = false;
      }, 1000);
      if (goodsList.value.length === totalCount.value) {
        // 数据加载完毕
        finished.value = true;
      }
    }
  });
};

onMounted(() => {
  getGoodsList();
});
</script>

<style></style>